package leetcode;

import java.util.ArrayList;

/**
 * Created by Ghost on 2014/12/23 0023.
 */
public class Fraction_to_Recurring_Decimal {
    public String fractionToDecimal(int numerator, int denominator) {
        boolean a=true,b=true;
        long num1 = numerator;
        long num2 = denominator;
        if(num1<0){
            a=false;
            num1 = -1*num1;
        }
        if(num2<0){
            b = false;
            num2 = -1*num2;
        }




        ArrayList<Long> yushu = new ArrayList<Long>();
        ArrayList<Long> yushuRst = new ArrayList<Long>();
        long integerPart = num1 / num2;
        long decimalPart = num1 % num2;
        if (decimalPart != 0) {
            boolean flag = false;
            while (!yushu.contains(decimalPart)) {
                long tmp = decimalPart * 10;
                yushu.add(decimalPart);
                yushuRst.add(tmp / num2);
                decimalPart = tmp % num2;
                if (decimalPart == 0) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                StringBuffer sb = new StringBuffer("");
                if((a&&!b)||(!a&&b))
                    sb.append("-");
                sb.append(integerPart + ".");
                for (Long i : yushuRst) {
                    sb.append(i);
                }

                return sb.toString();
            } else {
                StringBuffer sb = new StringBuffer("");
                if((a&&!b)||(!a&&b))
                    sb.append("-");
                sb.append(integerPart + ".");
                for (int i = 0; i < yushu.size(); i++) {
                    if (yushu.get(i) == decimalPart) {
                        sb.append("(");
                    }
                    sb.append(yushuRst.get(i));
                }

                sb.append(")");
                return sb.toString();
            }
        } else {
            if((a&&!b && integerPart!=0)||(!a&&b && integerPart!=0))
                return "-" + integerPart;
            else
                return ""+integerPart;

        }
    }

    public static void main(String[] args) {
        Fraction_to_Recurring_Decimal fraction_to_recurring_decimal = new Fraction_to_Recurring_Decimal();
        System.out.println(fraction_to_recurring_decimal.fractionToDecimal(1, -2147483647));//it won't work but received an accept!!
    }
}
